# Coze API 流式测试脚本
# 用途：快速测试 Coze API 的返回格式，查看奖励信息在哪个字段

# 配置参数（从 config.go 中复制）
$API_KEY = "pat_QluHFyDbjaVZpaxY3ROjirexeEkfWFnZrY4qnZi3yfi2SXBGTQrrYFzdDrpSxPwk"
$BOT_ID = "7558712880472834086"
$API_URL = "https://api.coze.cn/v3/chat"

# 测试场景1：首次历练（无 conversation_id）
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "测试场景1：首次历练" -ForegroundColor Cyan
Write-Host "========================================`n" -ForegroundColor Cyan

# 构造用户上下文数据（符合你的 AI Agent 要求）
$userContext = @{
    user_id = 123
    realm = "练气期"
    realm_level = "后期"
    talent = 70
    comprehension = 80
    luck = 70
    adventure_count = 3
    equipments = @(
        @{
            id = 201
            name = "青铜剑"
            type = "武器"
            effect = "攻击+10"
        },
        @{
            id = 202
            name = "护身符"
            type = "防具"
            effect = "防御+5"
        }
    )
    items = @(
        @{
            id = 301
            name = "火球符"
            type = "符箓"
            desc = "释放火球"
            effect = "伤害30"
        }
    )
}

# 将用户上下文转换为 JSON 字符串（作为 content）
$userContextJson = $userContext | ConvertTo-Json -Depth 10 -Compress

# 构造请求体（符合你的 curl 示例格式）
$requestBody = @{
    bot_id = $BOT_ID
    user_id = "123456789"
    stream = $true
    additional_messages = @(
        @{
            content = $userContextJson
            content_type = "text"
            role = "user"
            type = "question"
        }
    )
    parameters = @{}
} | ConvertTo-Json -Depth 10

Write-Host "请求URL: $API_URL" -ForegroundColor Yellow
Write-Host "请求体:" -ForegroundColor Yellow
Write-Host $requestBody -ForegroundColor Gray
Write-Host "`n开始请求...(流式输出)`n" -ForegroundColor Green

# 发送请求（流式）
try {
    $headers = @{
        "Authorization" = "Bearer $API_KEY"
        "Content-Type" = "application/json"
        "Accept" = "text/event-stream"
    }
    
    # 使用 Invoke-WebRequest 获取流式响应
    $response = Invoke-WebRequest -Uri $API_URL -Method Post -Headers $headers -Body $requestBody -TimeoutSec 60
    
    Write-Host "响应状态码: $($response.StatusCode)" -ForegroundColor Green
    Write-Host "`n完整响应内容:" -ForegroundColor Yellow
    Write-Host "========================================" -ForegroundColor Gray
    
    # 按行解析 SSE 格式
    $lines = $response.Content -split "`n"
    $conversationId = ""
    
    foreach ($line in $lines) {
        $line = $line.Trim()
        if ($line -eq "") { continue }
        
        # 高亮显示不同类型的行
        if ($line.StartsWith("event:")) {
            Write-Host $line -ForegroundColor Magenta
        }
        elseif ($line.StartsWith("data:")) {
            Write-Host $line -ForegroundColor Cyan
            
            # 尝试解析 JSON
            $jsonData = $line.Substring(5).Trim()
            try {
                $obj = $jsonData | ConvertFrom-Json
                
                # 查找 conversation_id
                if ($obj.conversation_id) {
                    $conversationId = $obj.conversation_id
                }
                
                # 美化显示关键字段
                Write-Host "  -> event: $($obj.event)" -ForegroundColor Yellow
                Write-Host "  -> conversation_id: $($obj.conversation_id)" -ForegroundColor Yellow
                
                if ($obj.message) {
                    Write-Host "  -> message.role: $($obj.message.role)" -ForegroundColor Green
                    Write-Host "  -> message.type: $($obj.message.type)" -ForegroundColor Green
                    Write-Host "  -> message.content: $($obj.message.content)" -ForegroundColor White
                }
            }
            catch {
                # JSON 解析失败，直接显示
                Write-Host "  (无法解析为JSON)" -ForegroundColor Red
            }
        }
        elseif ($line.StartsWith("id:")) {
            Write-Host $line -ForegroundColor DarkGray
        }
        else {
            Write-Host $line -ForegroundColor Gray
        }
    }
    
    Write-Host "`n========================================" -ForegroundColor Gray
    
    if ($conversationId) {
        Write-Host "`n✅ 成功获取 conversation_id: $conversationId" -ForegroundColor Green
        
        # 提示用户可以进行第二次测试
        Write-Host "`n是否继续测试场景2（用户作出选择）？[Y/N]" -ForegroundColor Yellow
        $continue = Read-Host
        
        if ($continue -eq "Y" -or $continue -eq "y") {
            Write-Host "`n========================================" -ForegroundColor Cyan
            Write-Host "测试场景2：用户作出选择（带 conversation_id）" -ForegroundColor Cyan
            Write-Host "========================================`n" -ForegroundColor Cyan
            
            # 构造第二次请求（带 conversation_id 和用户选择）
            # 模拟用户做出选择的场景
            $userChoiceContext = @{
                last_story = "你在密林中遇到一只灵兽，灵兽盯着你的青铜剑，似乎有所忌惮..."
                choices = @(
                    @{ id = 1; text = "与灵兽战斗" },
                    @{ id = 2; text = "尝试交流" },
                    @{ id = 3; text = "逃离密林" }
                )
                user_choice = 1
                user_context = $userContext
                history = @()
            }
            
            $userChoiceJson = $userChoiceContext | ConvertTo-Json -Depth 10 -Compress
            
            $requestBody2 = @{
                bot_id = $BOT_ID
                user_id = "123456789"
                stream = $true
                conversation_id = $conversationId
                additional_messages = @(
                    @{
                        content = $userChoiceJson
                        content_type = "text"
                        role = "user"
                        type = "question"
                    }
                )
                parameters = @{}
            } | ConvertTo-Json -Depth 10
            
            Write-Host "请求URL: ${API_URL}?conversation_id=$conversationId" -ForegroundColor Yellow
            Write-Host "请求体:" -ForegroundColor Yellow
            Write-Host $requestBody2 -ForegroundColor Gray
            Write-Host "`n开始请求...(流式输出)`n" -ForegroundColor Green
            
            $response2 = Invoke-WebRequest -Uri "${API_URL}?conversation_id=$conversationId" -Method Post -Headers $headers -Body $requestBody2 -TimeoutSec 60
            
            Write-Host "响应状态码: $($response2.StatusCode)" -ForegroundColor Green
            Write-Host "`n完整响应内容:" -ForegroundColor Yellow
            Write-Host "========================================" -ForegroundColor Gray
            
            $lines2 = $response2.Content -split "`n"
            foreach ($line in $lines2) {
                $line = $line.Trim()
                if ($line -eq "") { continue }
                
                if ($line.StartsWith("event:")) {
                    Write-Host $line -ForegroundColor Magenta
                }
                elseif ($line.StartsWith("data:")) {
                    Write-Host $line -ForegroundColor Cyan
                    
                    $jsonData = $line.Substring(5).Trim()
                    try {
                        $obj = $jsonData | ConvertFrom-Json
                        Write-Host "  -> event: $($obj.event)" -ForegroundColor Yellow
                        if ($obj.message) {
                            Write-Host "  -> message.content: $($obj.message.content)" -ForegroundColor White
                        }
                    }
                    catch {}
                }
                else {
                    Write-Host $line -ForegroundColor Gray
                }
            }
            
            Write-Host "`n========================================" -ForegroundColor Gray
        }
    }
    else {
        Write-Host "`n⚠️ 未找到 conversation_id" -ForegroundColor Red
    }
    
}
catch {
    Write-Host "`n❌ 请求失败:" -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Red
    
    if ($_.Exception.Response) {
        $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
        $responseBody = $reader.ReadToEnd()
        Write-Host "`n错误响应内容:" -ForegroundColor Red
        Write-Host $responseBody -ForegroundColor Gray
    }
}

Write-Host "`n测试完成！" -ForegroundColor Green
Write-Host "请查看上面的输出，重点关注：" -ForegroundColor Yellow
Write-Host "1. data: 行中的 JSON 结构" -ForegroundColor White
Write-Host "2. message.content 字段的内容格式" -ForegroundColor White
Write-Host "3. 是否有特定的 event 类型标识奖励信息" -ForegroundColor White
Write-Host "4. 奖励信息可能在哪个字段（content? metadata? custom_data?）" -ForegroundColor White
